define(['jquery',"bbcare","sortable","smartMenu","bld/app/patient/treatPlan.servers","bld/app/patient/treatPlan.ui"],function($,$bb,$sortable,$smartMenu,$servers,$ui){
    var treatPlan = {};
    var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
    var channelId = $bb.getChannelId();
    var sortable_courseStore,className = "treatPlanModal";;

    /**
     * 删除疗程回调函数
     */
    var ajaxRemoveCourse = function(data){
        $bb.toastShow('疗程删除成功');
        planInfo();
    }

    /**
     * 确认删除疗程
     */
    var confirmRemoveCourse = function(params){
        $servers.ajaxRemoveCourse(params,ajaxRemoveCourse);
    }

    /**
     * 删除疗程
     */
    var delCourse = function(el){
        var ptStageId = $(el).parent().parent().parent().attr('data-ptStageId');
        var ptCourseId = $(el).parent().attr('data-ptCourseId');
        var seqNo = parseInt($(el).parent().attr('data-seqNo'));
        var courseName = $(el).parent().find(".stage-course-name").html();
        var params = {
            "oprInfo":{
                "opCode": "1249",
                "opType": "2",
                "opNote": "【" + doctorName + "】医生删除疗程",
                "channelType": "2",
                "channelId": channelId
            },
            "ptStageId":ptStageId,
            "ptCourseId":ptCourseId,
            "seqNo":seqNo,
        };
        $bb.toastConfirmShow(confirmRemoveCourse,params,'是否确认删除' + courseName);
    };

    /**
     * 渲染右击疗程菜单
     */
    var renderCourseRightMenu = function(){
        $(".stage-course").bind("mousedown",function(e){
            if( e.which == 3 ){
                var courseName = $(e.target).parent().find(".stage-course-name").html();
                var stageName = $(e.target).parents(".stage-div").children(".stage-name").html();
                var ptCourseId = $(e.target).parent().attr('data-ptCourseId');
                var courseId = $(e.target).parent().attr('id');
                var opertion = {
                    name: courseId,
                    offsetX: 2,
                    offsetY: 2,
                    textLimit: 10,
                    beforeShow: function() {
                        $.smartMenu.remove();
                    },
                    afterShow: function() {
                        //$.smartMenu.remove();
                    }
                };
                var imageMenuData = [
                    [
                        {
                            text: "编辑疗程",
                            func: function() {
                                var params = { 
                                    "courseName": courseName,
                                    "stageName":stageName,
                                    "ptCourseId":ptCourseId,
                                    "id": courseId,
                                };
                                params.info = $bb.getPageParams();
                                $bb.openPage('bld_treatPlanCourseEdit',params);
                            }
                        }, 
                        {
                            text: "删除" + '[' + courseName  + ']',
                            func: function() {
                                delCourse(e.target);
                            }
                        }
                    ]
                ];
                $(this).smartMenu(imageMenuData,opertion);
            }
        });
    }

    /************************ 插入治疗方案 begin 代码未查，不可用 ************************/
    
    /**
     * 插入治疗方案回调函数
     */
    var ajaxIsnertScheme = function(data) {
        $('.treatPlanModal').modal('hide');
        $servers.ajaxGetPtDisPlanInfo({}, ajaxGetPtDisPlanInfo);
    }

    var addClassify = function(){
        var schemeId = $('#schemeId').val();
        var params = {};
        params['oprInfo'] = {
            "opCode": "2053",
            "opType": "3",
            "opNote": "【" + doctorName + "】医生插入治疗方案",
            "channelType": "2",
            "channelId": channelId
        };
        params['planInfo'] = {
            "id": planId,
            "ptSchemeId": ptSchemeId,
            "userId": userId,
            "queueId": queueId,
            "schemeId": schemeId,
            "schemeVersion": 1,
            "groupType": "",
            "startStageSeqNo": 1,
            "endStageSeqNo": 1,
            "startCourseSeqNo": $('#startCourseSeqNo').attr('data-index'),
            "endCourseSeqNo": $('#endCourseSeqNo').attr('data-index'),
            "insertStageSeqNo": $(this).data('data')
        };
        $servers.ajaxIsnertScheme(params, ajaxIsnertScheme);
    }

    /**
     * 模态框疗程回调函数
     */
    var ajaxAllCourse = function(data) {
        $ui.allCourse({
            "id": "startCourseSeqNo",
            "list": data.rows
        });
        $ui.allCourse({
            "id": "endCourseSeqNo",
            "list": data.rows
        });
    }

    var onChangeSchemeCourse = function(){
        var params = {};
        var schemeId = $("#schemeId").val();
        params["queryCriteria"] = {
            "courseName": '',
            "schemeId": schemeId,
            "groupType": '',
            "classId": "",
            "groupType": "",
            "courseType": "",
            "courseId": "",
            "status": "1"
        }
        $servers.ajaxQueryAllCourse(params,ajaxAllCourse);
    }

    /**
     * 获取所有方案库模态框回调函数
     */
    var ajaxAllScheme = function(data) {
        $ui.allScheme({
            "id": "schemeId",
            "list": data.schemeClassInfos
        })
        $('#schemeId').unbind("change");
        $('#schemeId').bind("change", onChangeSchemeCourse);
        $('#schemeId').trigger("change");
    }

    /**
     * 插入方案 ???
     */
    var onAddClassify = function(el){
        $bb.modal({
            "className": className,
            "tit": "插入方案",
        }, function() {
            $ui.addClassify({
                "dom": $("." + className + " .modal-body"),
            });
            $("." + className).modal("show");
            $servers.ajaxQueryAllScheme(ajaxAllScheme);
            var seqNo = $(el).parent().index() + 2;
            $("#add").unbind('click');
            $("#add").data('data', seqNo);
            $("#add").click(addClassify);
        })
    }

    /************************ 插入治疗方案 end 代码未查，不可用 ************************/

    /*删除阶段回调函数 */
    var ajaxRemoveStage = function(data){
        $bb.toastShow('删除阶段成功');
        planInfo();
    }
    /*确认删除阶段 */
    var confirmRemoveStage = function(params){
        $servers.ajaxRemoveStage(params,ajaxRemoveStage);
    }

    /**
     * 删除阶段
     */
    var delStage = function(el){
        var ptStageId = $(el).parent().attr('data-ptStageId');
        var stageName = $(el).html();
        var params = {
            "oprInfo":{
                "opCode": "1245",
                "opType": "2",
                "opNote": "【" + doctorName + "】医生删除阶段",
                "channelType": "2",
                "channelId": channelId
            },
            "stageInfo":{
                "id": ptStageId
            }
        };
        $bb.toastConfirmShow(confirmRemoveStage,params,'是否确认删除' + stageName);
    };

    /**
     * 添加阶段成功后的回调函数
     */
    var ajaxAddStage = function(data){
        $('.' + className).modal('hide');
        $bb.toastShow('添加阶段成功');
        planInfo();
    }

    /**
     * 添加阶段
     */
    var addStage = function(){
        var arg = $(this).data("arg");
        var ptStageName = $('#ptStageName').val();
        if( ptStageName == '' ){
            $('#ptStageName').focus();
        }else{
            var seqNo = arg.dom.parent().index() + 2;
            var params = {
                "oprInfo":{
                    "opCode": "1244",
                    "opType": "2",
                    "opNote": "【" + doctorName + "】医生添加阶段",
                    "channelType": "2",
                    "channelId": channelId
                },
                "stageInfo":{
                    "userId": arg.datas.info.userId,
                    "queueId": arg.datas.info.queueId,
                    "planId": arg.datas.ptDisPlan.planId,
                    "seqNo": seqNo,
                    "stageName": ptStageName
                }
            };
            $servers.ajaxAddStage(params,ajaxAddStage);
        }
    }

    /**
     * 添加阶段
     */
    var onAddStage = function(el,datas){
        $bb.modal({
            "className": className,
            "tit": "请输入阶段名称",
            "size":"modal-sm"
        }, function() {
            $ui.addStage({
                "dom": $("." + className + " .modal-body"),
            });
            $("." + className).modal("show");
            $("#add").unbind("click");
            $("#add").data("arg",{"dom":$(el),"datas":datas});
            $("#add").click(addStage);
        });
    }

    /**
     * 修改阶段名称成功后的回调函数
     */
    var ajaxChangeStageName = function(data){
        $('.' + className).modal('hide');
        $bb.toastShow('阶段名称修改成功');
        planInfo();
    }

    /**
     * 修改阶段名称
     */
    var modifyStage = function(){
        var ptStageName = $('#ptStageName').val();
        var $dom = $(this).data("dom");
        if ( ptStageName == '' ) {
            $('#ptStageName').focus();
        }else{
            var ptStageId = $dom.parent().attr('data-ptStageId');
            var params = {
                "oprInfo":{
                    "opCode": "1246",
                    "opType": "2",
                    "opNote": "【" + doctorName + "】医生修改阶段名称",
                    "channelType": "2",
                    "channelId": channelId
                },
                "ptStageId":ptStageId,
                "ptStageName":ptStageName
            };
            $servers.ajaxChangeStageName(params,ajaxChangeStageName);
        }        
    }

    /**
     * 编辑阶段名
     */
    var onModifyStage = function(el){
        $bb.modal({
            "className": className,
            "tit": "请输入阶段名称",
            "size":"modal-sm"
        }, function() {
            var stageName = $(el).html();
            $ui.modifyStageName({
                "dom": $("." + className + " .modal-body"),
                "stageName": stageName
            });
            $("." + className).modal("show");
            $("#modify").unbind("click");
            $("#modify").data("dom",$(el));
            $("#modify").click(modifyStage);
        });
    }

    /**
     * 右击阶段菜
     */
    var renderStageRightMenu = function(datas){
        $(".stage-name").each(function(i,ele){
            var imageMenuData = [
                [
                    {
                        text: "编辑阶段名",
                        func: function() {
                            onModifyStage(ele);
                        }
                    },
                    /*{
                        text: "插入方案",
                        func: function() {
                            onAddClassify(ele);
                        }
                    }, */
                    {
                        text: "插入阶段",
                        func: function() {
                            onAddStage(ele,datas);
                        }
                    }, 
                    {
                        text: "删除" + '[' + $(ele).html() + ']',
                        func: function() {
                            delStage(ele);
                        }
                    }
                ]
            ];
            $(ele).bind("mousedown", function(e){
                if(e.which == 3){
                    var opertion = {
                        name: $(ele).html(),
                        offsetX: 2,
                        offsetY: 2,
                        textLimit: 10,
                        beforeShow: function() {
                            $.smartMenu.remove();
                        },
                        afterShow: $.noop
                    };
                    $(this).smartMenu(imageMenuData,opertion);
                }
            });
        });
    };

    /**
     * 添加疗程回调函数
     */
    var ajaxAddCourse = function(data){
        $bb.toastShow('添加疗程成功');
        planInfo();
    }

    /**
     * 上下移动疗程回调函数
     */
    var ajaxMoveCourse = function(data){
        planInfo();
    }

    /**
     * 初始化绑定元素
     */
    var initSortable = function(datas){
        if(sortable_courseStore) sortable_courseStore.destroy();
        // 添加疗程
        sortable_courseStore = $sortable.create($("#courseStore")[0],{
            sort: true,
            group: {
                name: 'advanced',
                pull: "clone",
                put: false
            },
            onEnd: function(target){
                var $dom = $(target.item);
                // 放置在dom元素class名为stage-course-list里
                if( !$dom.parents(".stage-course-list").length ) return;
                var olderIndex = target.oldIndex;
                if( !$dom.parents("#courseStore").length ){
                    var seqNo = $dom.siblings(".stage-null").length > 0 ? 1 : $dom.prevAll().length + 1;
                    var stageSeqNo = $dom.parents("stage-div").prevAll().length + 1;
                    var params = {
                        "oprInfo":{
                            "opCode": "1247",
                            "opType": "2",
                            "opNote": "【" + doctorName + "】医生添加疗程",
                            "channelType": "2",
                            "channelId": channelId
                        },
                        "courseInfo":{                            
                            "userId": datas.info.userId,
                            "queueId": datas.info.queueId,
                            "planId": datas.ptDisPlan.planId,
                            "ptStageId": $dom.parents(".stage-div").attr("data-ptStageId"),
                            "courseId": $dom.attr("id"),
                            "courseVersion": parseInt($dom.attr("data-version")),
                            "seqNo": seqNo,
                            "stageSeqNo": stageSeqNo
                        }
                    };
                    $servers.ajaxAddCourse(params,ajaxAddCourse);
                }
            },
            animation: 150
        });
        // 移动疗程
        $(".stage-course-list").each(function(index,el){
            $sortable.create(el,{
                sort: true,
                group: {
                    name: 'advanced',
                    pull: false,
                    put: true
                },
                onEnd: function(target) {
                    if(target.newIndex == target.oldIndex) return false;
                    target = target.item;
                    if(!$(target).parents("#courseStore").length){
                        var dom = $(target);
                        var params = {
                            "oprInfo":{
                                "opCode": "1248",
                                "opType": "2",
                                "opNote": "【" + doctorName + "】医生移动疗程",
                                "channelType": "2",
                                "channelId": channelId
                            },
                            "ptStageId":dom.parent().parent().attr('data-ptstageid'),
                            "ptCourseId":dom.attr('data-ptcourseid'),
                            "seqNo":dom.index() + 1,
                        };
                        $servers.ajaxMoveCourse(params,ajaxMoveCourse);
                    }
                },
                animation: 150
            });
        });
    };

    /**
     * 获取治疗计划详细信息回调函数
     */
    var ajaxGetPtDisPlanInfo = function(data,info){
        data = data[0];
        $ui.getPlanDetail({
            "id": "planInfo",
            "list": data.ptDisStagePOs
        });
        var datas = {};
        datas.ptDisPlan = data;
        datas.info = info;
        // 添加疗程、疗程排序
        initSortable(datas);
        // 右击阶段菜单
        renderStageRightMenu(datas);
        // 渲染右击疗程菜单
        renderCourseRightMenu();
    }

    /**
     * 请求治疗计划详情
     */
    var planInfo = function(){
        var info = $bb.getPageParams();
        // 获取治疗计划详细信息
        $servers.ajaxGetPtDisPlanInfo(info,ajaxGetPtDisPlanInfo);
    }

    /**
     * 查询疗程信息回调函数
     */
    var ajaxQueryAllCourse = function(data) {
        $ui.queryAllCourse({
            "id": "courseStore",
            "list": data.rows
        });
        planInfo();
    }

    /**
     * 切换方案下的疗程
     */
    var onChangeCourse = function(){
        var classId = $(this).val();
        var params = {
            "queryCriteria":{
                "schemeId": classId,
                "status": "1"
            }
        };
        $servers.ajaxQueryAllCourse(params,ajaxQueryAllCourse);
    }

    /**
     * 请求所有方案分类成功后的回调函数
     */
    var ajaxQueryAllScheme = function(data){
        $ui.queryAllScheme({
            "id": "classify",
            "list": data.schemeClassInfos
        });
        $('#classify').unbind("change");
        $('#classify').bind("change",onChangeCourse);
        $('#classify').trigger("change");
    }

    treatPlan.init = function() {
        var info = $bb.getPageParams();
        // 基本信息
        $ui.info({
            "id":"treatPlanInfo",
            "info":info
        });
        // 请求所有方案分类
        $servers.ajaxQueryAllScheme(ajaxQueryAllScheme);
        // 疗程库展开与折叠
        $(".showCourseStore").unbind('click');
        $(".showCourseStore").click(function(){
            $("#courseStore").toggle(500,function(){});
        });
    };

    return treatPlan;
});